# -*- coding: utf-8 -*-
# @Author: XiaoRui
# @FileName: run.py
# @Time: 2021/4/20 10:28
# @Software: PyCharm

import json
import math
import datetime
import numpy as np
import configparser
from .import NODE 
from .import udp  as udp
# from .import pipe  as pipe
from .import dlltest  as dlltest
from .import globalvar  as Globalvar

# from NODE import *
# from udp import *
# from pipe import *
# import globalvar as Globalvar
# from dlltest import *
import operator

# node1：对应于osm_id在0-100之间节点
node1 = []
# node2：对应于osm_id在101-200之间节点
node2 = []
# node3：对应于osm_id在201-300之间节点
node3 = []
# node4：对应于osm_id在301-400之间节点
node4 = []
# node5：对应于osm_id在401-500之间节点
node5 = []
# node6：对应于osm_id在501-600之间节点
node6 = []
# node7：对应于osm_id在601-700之间节点
node7 = []
# 由node1-7组成，便于查找方便
nodeList = [node1, node2, node3, node4, node5, node6, node7]
errorThreshold = 4e-7
errorThreshold2 = 4e-6
new_numlist = {}
# 为new_numlist做补充
del_numlist = {}
# 更新del_numlist用
update_del_numlist = {}


def read_map():
    find_flag = False
    # RoadLines = json.load(open("C:/Users/sk/Desktop/ronghuizhitong/Test_Exam/session/map/RoadLine.json",
    #                            "r", encoding="utf-8"))
    # RoadPoints = json.load(open("C:/Users/sk/Desktop/ronghuizhitong/Test_Exam/session/map/RoadPoint.json",
    #                             "r", encoding="utf-8"))
    RoadLines = json.load(open("D:/session/map/RoadLine.json", "r", encoding="utf-8"))
    RoadPoints = json.load(open("D:/session/map/RoadPoint.json", "r", encoding="utf-8"))
    # 对数据中的经纬度保留小数点后7位
    for i in range(len(RoadLines)):
        for j in range(len(RoadLines[i]["geometry"]["coordinates"])):
            RoadLines[i]["geometry"]["coordinates"][j][0] = float(format(RoadLines[i]["geometry"]["coordinates"][j][0], ".8f"))
            RoadLines[i]["geometry"]["coordinates"][j][1] = float(format(RoadLines[i]["geometry"]["coordinates"][j][1], ".8f"))
    for i in range(len(RoadPoints)):
        RoadPoints[i]["geometry"]["coordinates"][0] = float(format(RoadPoints[i]["geometry"]["coordinates"][0], ".8f"))
        RoadPoints[i]["geometry"]["coordinates"][1] = float(format(RoadPoints[i]["geometry"]["coordinates"][1], ".8f"))
    # 删除RoadPoints中重复的、反向的
    del_points = []
    for i in range(len(RoadPoints) - 1):
        if RoadPoints[i]["properties"]["osm_id"] != RoadPoints[i]["properties"]["osm_id_2"]:
            for j in range(i + 1, len(RoadPoints)):
                if RoadPoints[i]["geometry"]["coordinates"] == RoadPoints[j]["geometry"]["coordinates"]:
                    l1 = list(RoadPoints[i]["properties"].values())
                    l2 = list(RoadPoints[j]["properties"].values())
                    l1.sort()
                    l2.sort()
                    if l1 == l2:
                        del_points.append(j)
                        break
        else:
            del_points.append(i)
    del_points.sort(reverse=True)
    for index in del_points:
        # print(RoadPoints[index])
        del RoadPoints[index]

    # 删除RoadLines中经纬度均为同一个的路（只删除路上的最后一个点）
    # print(sum([len(x["geometry"]["coordinates"]) for x in RoadLines]))
    del1 = []
    for i in range(len(RoadLines)):
        count1 = 0
        for j in range(len(RoadLines[i]["geometry"]["coordinates"])):
            if j == 0:
                temp_value = RoadLines[i]["geometry"]["coordinates"][0]
                count1 += 1
            else:
                if temp_value == RoadLines[i]["geometry"]["coordinates"][j]:
                    count1 += 1
                if count1 == len(RoadLines[i]["geometry"]["coordinates"]):
                    # print(str(RoadLines[i]["properties"]["osm_id"]) + " " + str(RoadLines[i]["geometry"]["coordinates"]))
                    del1.append(i)
                    break
    del1.sort(reverse=True)
    for index in del1:
        del RoadLines[index]["geometry"]["coordinates"][-1]
        # del RoadLines[index]

    # 按osm_id对道路升序排序
    RoadLines.sort(key=lambda x: x["properties"]["osm_id"])

    # 删除经纬度为空的道路
    del_lines2 = []
    for i in range(len(RoadLines)):
        if not RoadLines[i]["geometry"]["coordinates"]:
            del_lines2.append(i)
    del_lines2 = list(set(del_lines2))
    del_lines2.sort(reverse=True)
    for index in del_lines2:
        del RoadLines[index]

    # 删除RoadLines中多段首尾相连的路
    # print(sum([len(x["geometry"]["coordinates"]) for x in RoadLines]))
    del_lines = []
    index_error = 0
    i1 = 0
    while i1 <= len(RoadLines) - 1:
        for j in range(i1 + 1, len(RoadLines)):
            index_error = j - i1
            # 在osm_id一致的情况下
            if RoadLines[i1]["properties"]["osm_id"] == RoadLines[j]["properties"]["osm_id"]:
                longitude_error1 = math.fabs(
                    RoadLines[i1]["geometry"]["coordinates"][-1][0] - RoadLines[j]["geometry"]["coordinates"][0][0])
                latitude_error1 = math.fabs(
                    RoadLines[i1]["geometry"]["coordinates"][-1][1] - RoadLines[j]["geometry"]["coordinates"][0][1])
                if ((longitude_error1 <= errorThreshold and latitude_error1 <= errorThreshold) or
                        (longitude_error1 == 0 and latitude_error1 <= errorThreshold2) or (longitude_error1 <= errorThreshold2 and latitude_error1 == 0)):
                    # 同一条路的上段和下段首尾相连时，将下条路的后续节点添加到上条路最后节点的子节点中，删除下条路
                    # print(str(RoadLines[i1]["properties"]["osm_id"]) + " " + str(RoadLines[i1]["geometry"]["coordinates"]))
                    RoadLines[i1]["geometry"]["coordinates"].extend(RoadLines[j]["geometry"]["coordinates"][1:])
                    # print(str(RoadLines[i1]["properties"]["osm_id"]) + " " + str(RoadLines[i1]["geometry"]["coordinates"]))
                    del_lines.append(j)
                # 上一段路的第一个和下段路的最后一个
                longitude_error2 = math.fabs(
                    RoadLines[i1]["geometry"]["coordinates"][0][0] - RoadLines[j]["geometry"]["coordinates"][-1][0])
                latitude_error2 = math.fabs(
                    RoadLines[i1]["geometry"]["coordinates"][0][1] - RoadLines[j]["geometry"]["coordinates"][-1][1])
                if ((longitude_error2 <= errorThreshold and latitude_error2 <= errorThreshold) or
                        (longitude_error2 == 0 and latitude_error2 <= errorThreshold2) or (longitude_error2 <= errorThreshold2 and latitude_error2 == 0)):
                    # print(str(RoadLines[j]["properties"]["osm_id"]) + " " + str(RoadLines[j]["geometry"]["coordinates"]))
                    RoadLines[j]["geometry"]["coordinates"].extend(RoadLines[i1]["geometry"]["coordinates"][1:])
                    # print(str(RoadLines[j]["properties"]["osm_id"]) + " " + str(RoadLines[j]["geometry"]["coordinates"]))
                    del_lines.append(i1)
            else:
                break
        i1 += index_error
    del_lines = list(set(del_lines))
    del_lines.sort(reverse=True)
    for index in del_lines:
        del RoadLines[index]
    # print(sum([len(x["geometry"]["coordinates"]) for x in RoadLines]))

    # 每个RoadLines中经纬度相同的点删除
    del_lines1 = {}
    for k in range(len(RoadLines)):
        for i in range(len(RoadLines[k]["geometry"]["coordinates"]) - 1, 0, -1):
            for j in range(i - 1, -1, -1):
                # 如果相邻两个点的经纬度一致则删除
                if operator.eq(RoadLines[k]["geometry"]["coordinates"][i], RoadLines[k]["geometry"]["coordinates"][j]):
                    del_lines1.setdefault(str(k), []).append(j)
                    # print(str(RoadLines[k]["properties"]["osm_id"]) + ": " + str(i) + str(RoadLines[k]["geometry"]["coordinates"][i]))
                    # print(str(RoadLines[k]["properties"]["osm_id"]) + ": " + str(j) + str(RoadLines[k]["geometry"]["coordinates"][j]))
    for key, value in del_lines1.items():
        value = list(set(value))
        value.sort(reverse=True)
        for v in value:
            del RoadLines[int(key)]["geometry"]["coordinates"][v]
    # print(sum([len(x["geometry"]["coordinates"]) for x in RoadLines]))

    # 标记V、Y类型的道路（osm_id一致）
    marked_lines = {}
    for i in range(len(RoadLines) - 1):
        for j in range(i + 1, len(RoadLines)):
            # 在osm_id一致的情况下
            if RoadLines[i]["properties"]["osm_id"] == RoadLines[j]["properties"]["osm_id"]:
                if RoadLines[i]["geometry"]["coordinates"][0] == RoadLines[j]["geometry"]["coordinates"][0]:
                    marked_lines.setdefault(str(RoadLines[i]["properties"]["osm_id"]), []).append(i)
                    marked_lines.setdefault(str(RoadLines[i]["properties"]["osm_id"]), []).append(j)
                    marked_lines.setdefault(str(RoadLines[i]["properties"]["osm_id"]), []).append(RoadLines[i]["geometry"]["coordinates"][0])
                else:
                    for k1 in range(len(RoadLines[i]["geometry"]["coordinates"])):
                        for k2 in range(len(RoadLines[j]["geometry"]["coordinates"])):
                            if RoadLines[i]["geometry"]["coordinates"][k1] == RoadLines[j]["geometry"]["coordinates"][k2]:
                                marked_lines.setdefault(str(RoadLines[i]["properties"]["osm_id"]), []).append(i)
                                marked_lines.setdefault(str(RoadLines[i]["properties"]["osm_id"]), []).append(j)
                                marked_lines.setdefault(str(RoadLines[i]["properties"]["osm_id"]), []).append(RoadLines[i]["geometry"]["coordinates"][k1])
            else:
                break

    # 将RoadLines中的数据处理为节点列表
    for i in range(len(RoadLines)):
        for j in range(len(RoadLines[i]["geometry"]["coordinates"])):
            if j == len(RoadLines[i]["geometry"]["coordinates"]) - 1:
                pnode = NODE.Node(RoadLines[i], RoadLines[i]["geometry"]["coordinates"][j], [])
            else:
                pnode = NODE.Node(RoadLines[i], RoadLines[i]["geometry"]["coordinates"][j], RoadLines[i]["geometry"]["coordinates"][j + 1])
            # 判断节点所在区间
            node_interval = NODE.which_interval(pnode.road_osm_id[0])
            nodeList[node_interval].append(pnode)
    print(sum([len(x) for x in nodeList]))

    # 合并V、Y类的交叉点
    del_nodes = {}
    for key, value in marked_lines.items():
        interval3 = NODE.which_interval(int(key))
        for i in range(len(nodeList[interval3]) - 1):
            for j in range(i + 1, len(nodeList[interval3])):
                if nodeList[interval3][i].road_osm_id == nodeList[interval3][j].road_osm_id:
                    if ((int(key) in nodeList[interval3][i].road_osm_id and int(key) in nodeList[interval3][j].road_osm_id) and
                            (value[-1] == nodeList[interval3][i].node_coordinates and value[-1] == nodeList[interval3][j].node_coordinates)):
                        nodeList[interval3][i].node_childrenNames.extend(nodeList[interval3][j].node_childrenNames)
                        nodeList[interval3][i].node_childrenNodes.extend(nodeList[interval3][j].node_childrenNodes)
                        del_nodes.setdefault(str(interval3), []).append(j)
                        del_numlist[str(nodeList[interval3][j].nodeName)] = nodeList[interval3][i].nodeName
                else:
                    break
    for key, value in del_nodes.items():
        value = list(set(value))
        del_nodes[key].sort(reverse=True)
        for v in value:
            del nodeList[int(key)][v]
    # print(sum([len(x) for x in nodeList]))

    # 添加路口节点
    temp_dict = {}
    points = {}
    del_nodes1 = {}
    for i in range(len(RoadPoints)):
        interval = NODE.which_interval(RoadPoints[i]["properties"]["osm_id"])
        interval2 = NODE.which_interval(RoadPoints[i]["properties"]["osm_id_2"])
        for j in range(len(nodeList[interval])):
            if (RoadPoints[i]["geometry"]["coordinates"] == nodeList[interval][j].node_coordinates and
                    (RoadPoints[i]["properties"]["osm_id"] in nodeList[interval][j].road_osm_id)):
                for k in range(len(nodeList[interval2])):
                    if (RoadPoints[i]["geometry"]["coordinates"] == nodeList[interval2][k].node_coordinates and
                            (RoadPoints[i]["properties"]["osm_id_2"] in nodeList[interval2][k].road_osm_id)):
                        # nodeList[interval][j].node_childrenNodes.extend(nodeList[interval2][k].node_childrenNodes)
                        # nodeList[interval][j].node_childrenNames.extend(nodeList[interval2][k].node_childrenNames)
                        # nodeList[interval][j].road_wide.extend(nodeList[interval2][k].road_wide)
                        # nodeList[interval][j].road_spide.extend(nodeList[interval2][k].road_spide)
                        # nodeList[interval][j].road_osm_id.append(RoadPoints[i]["properties"]["osm_id_2"])
                        # # 记录被删除的节点
                        # # print("parent node: " + str(nodeList[interval][j].nodeName) + "\t" + str(interval) + "\t" + str(j))
                        # # print("delete node: " + str(nodeList[interval2][k].nodeName) + "\t" + str(interval2) + "\t" + str(k))
                        # del_numlist[str(nodeList[interval2][k].nodeName)] = nodeList[interval][j].nodeName
                        # del_nodes1.setdefault(str(interval2), []).append(k)
                        # 判断路口是不是第一次出现，不是进入else
                        if str(RoadPoints[i]["geometry"]["coordinates"]) not in points.keys():
                            nodeList[interval][j].node_childrenNodes.extend(nodeList[interval2][k].node_childrenNodes)
                            nodeList[interval][j].node_childrenNames.extend(nodeList[interval2][k].node_childrenNames)
                            nodeList[interval][j].road_wide.extend(nodeList[interval2][k].road_wide)
                            nodeList[interval][j].road_spide.extend(nodeList[interval2][k].road_spide)
                            nodeList[interval][j].road_osm_id.append(RoadPoints[i]["properties"]["osm_id_2"])
                            # 记录被删除的节点
                            # print("parent node: " + str(nodeList[interval][j].nodeName) + "\t" + str(interval) + "\t" + str(j))
                            # print("delete node: " + str(nodeList[interval2][k].nodeName) + "\t" + str(interval2) + "\t" + str(k))
                            del_numlist[str(nodeList[interval2][k].nodeName)] = nodeList[interval][j].nodeName
                            del_nodes1.setdefault(str(interval2), []).append(k)
                            # 记录经纬度对应osm_id
                            temp_dict.setdefault(str(RoadPoints[i]["geometry"]["coordinates"]), []).append(RoadPoints[i]["properties"]["osm_id"])
                            temp_dict.setdefault(str(RoadPoints[i]["geometry"]["coordinates"]), []).append(RoadPoints[i]["properties"]["osm_id_2"])
                            # 记录第一次信息合并在哪个点上
                            points.setdefault(str(RoadPoints[i]["geometry"]["coordinates"]), []).append(interval)
                            points.setdefault(str(RoadPoints[i]["geometry"]["coordinates"]), []).append(j)
                        else:
                            # print("AAAAAAAAAAAAAAAAAAAAAA")
                            tmp = str(RoadPoints[i]["geometry"]["coordinates"])
                            # 如果是id已经重复出现
                            if RoadPoints[i]["properties"]["osm_id"] in temp_dict[str(RoadPoints[i]["geometry"]["coordinates"])]:
                                nodeList[points[tmp][0]][points[tmp][1]].node_childrenNodes.extend(nodeList[interval2][k].node_childrenNodes)
                                nodeList[points[tmp][0]][points[tmp][1]].node_childrenNames.extend(nodeList[interval2][k].node_childrenNames)
                                nodeList[points[tmp][0]][points[tmp][1]].road_wide.extend(nodeList[interval2][k].road_wide)
                                nodeList[points[tmp][0]][points[tmp][1]].road_spide.extend(nodeList[interval2][k].road_spide)
                                nodeList[points[tmp][0]][points[tmp][1]].road_osm_id.append(RoadPoints[i]["properties"]["osm_id_2"])
                                del_numlist[str(nodeList[interval2][k].nodeName)] = nodeList[points[tmp][0]][points[tmp][1]].nodeName
                                del_nodes1.setdefault(str(interval2), []).append(k)
                                temp_dict[str(RoadPoints[i]["geometry"]["coordinates"])].append(RoadPoints[i]["properties"]["osm_id_2"])
                            # 如果是id2重复出现
                            elif RoadPoints[i]["properties"]["osm_id_2"] in temp_dict[str(RoadPoints[i]["geometry"]["coordinates"])]:
                                nodeList[points[tmp][0]][points[tmp][1]].node_childrenNodes.extend(nodeList[interval][j].node_childrenNodes)
                                nodeList[points[tmp][0]][points[tmp][1]].node_childrenNames.extend(nodeList[interval][j].node_childrenNames)
                                nodeList[points[tmp][0]][points[tmp][1]].road_wide.extend(nodeList[interval][j].road_wide)
                                nodeList[points[tmp][0]][points[tmp][1]].road_spide.extend(nodeList[interval][j].road_spide)
                                nodeList[points[tmp][0]][points[tmp][1]].road_osm_id.append(RoadPoints[i]["properties"]["osm_id"])
                                del_numlist[str(nodeList[interval][j].nodeName)] = nodeList[points[tmp][0]][points[tmp][1]].nodeName
                                del_nodes1.setdefault(str(interval), []).append(j)
                                temp_dict[str(RoadPoints[i]["geometry"]["coordinates"])].append(RoadPoints[i]["properties"]["osm_id"])
                        find_flag = True
                        break
                if find_flag:
                    find_flag = False
                    break
    for key, value in del_nodes1.items():
        value = list(set(value))
        value.sort(reverse=True)
        for v in value:
            # print(key + "\t" + str(v) + "\t" + str(nodeList[int(key)][v].nodeName) + "\t" + str(nodeList[int(key)][v].node_coordinates))
            del nodeList[int(key)][v]
    print(sum([len(x) for x in nodeList]))

    # 合并经纬度一致的点
    temp_nodelist = []
    for i in range(len(nodeList)):
        for j in range(len(nodeList[i])):
            # nodelist展开
            temp_nodelist.append(nodeList[i][j])
    del_nodes2 = []
    points1 = []
    for i in range(len(temp_nodelist)-1):
        for j in range(i+1, len(temp_nodelist)):
            # 经纬度一致则合并
            if (temp_nodelist[i].node_coordinates == temp_nodelist[j].node_coordinates) and (temp_nodelist[i].node_coordinates not in points1):
                # print(str(temp_nodelist[i].nodeName) + ":" + str(i) + " " + str(temp_nodelist[j].nodeName) + ":" + str(j) + " " + str(temp_nodelist[i].node_coordinates) +
                #       str(temp_nodelist[i].road_osm_id) + " " + str(temp_nodelist[j].road_osm_id))
                temp_nodelist[i].node_childrenNodes.extend(temp_nodelist[j].node_childrenNodes)
                temp_nodelist[i].node_childrenNames.extend(temp_nodelist[j].node_childrenNames)
                temp_nodelist[i].road_wide.extend(temp_nodelist[j].road_wide)
                temp_nodelist[i].road_spide.extend(temp_nodelist[j].road_spide)
                temp_nodelist[i].road_osm_id.extend(temp_nodelist[j].road_osm_id)
                del_nodes2.append(j)
                update_del_numlist[str(temp_nodelist[j].nodeName)] = temp_nodelist[i].nodeName
        points1.append(temp_nodelist[i].node_coordinates)
    del_nodes2 = list(set(del_nodes2))
    del_nodes2.sort(reverse=True)
    for delIndex in del_nodes2:
        del temp_nodelist[delIndex]
    # nodelist清空
    for i in range(len(nodeList)):
        nodeList[i].clear()
    # 重新生成nodelist
    for eachnode in temp_nodelist:
        nodeList[NODE.which_interval(eachnode.road_osm_id[0])].append(eachnode)
    # 更新del_numlist
    for k1, v1 in del_numlist.items():
        for k2, v2 in update_del_numlist.items():
            if int(k2) == v1:
                del_numlist[k1] = v2
    del_numlist.update(update_del_numlist)
    print(sum([len(x) for x in nodeList]))

    # 对nodelist中的节点重新编号
    for i in range(len(nodeList)):
        for j, element in enumerate(nodeList[i]):
            if i == 0:
                # 判断节点编号是否变化
                if element.nodeName != j:
                    new_numlist[str(element.nodeName)] = j
                    for key, value in del_numlist.items():
                        if value == element.nodeName:
                            del_numlist[key] = j
                            # print("del_numlist: " + key + ": " + str(value) + " " + str(j))
                    element.nodeName = j
            else:
                temp_name = j
                for k in range(i):
                    temp_name += len(nodeList[k])
                # 判断节点编号是否变化
                if element.nodeName != temp_name:
                    new_numlist[str(element.nodeName)] = temp_name
                    for key, value in del_numlist.items():
                        if value == element.nodeName:
                            del_numlist[key] = temp_name
                            # print("del_numlist: " + key + ": " + str(value) + " " + str(temp_name))
                    element.nodeName = temp_name

    # 对节点的子节点编号更改
    new_numlist.update(del_numlist)
    for i in range(len(nodeList)):
        for j in range(len(nodeList[i])):
            # 非空
            if nodeList[i][j].node_childrenNames:
                for k in range(len(nodeList[i][j].node_childrenNames)):
                    if str(nodeList[i][j].node_childrenNames[k]) in new_numlist.keys():
                        temp_index = str(nodeList[i][j].node_childrenNames[k])
                        # print("node name: " + str(nodeList[i][j].nodeName) + " oldchildren name: " + temp_index + " newchildren name: " + str(new_numlist[temp_index]))
                        nodeList[i][j].node_childrenNames[k] = new_numlist[temp_index]
    # print(nodeList)

def read_client_path(session, subject, exam_round=1):
    # 读取相应的client_path_.json文件
    # json_path = "C:/Users/sk/Desktop/ronghuizhitong/Test_Exam/session/session_1/subject_1/client_path_1.json"
    json_path = "D:/session/session_1/subject_1/client_path_1.json"
    # 科目一
    if session == 1:
        if subject == 2:
            json_path = json_path.replace("subject_1", "subject_2")
    # 科目二
    elif session == 2:
        json_path = json_path.replace("session_1", "session_2")
        # 情景2
        if subject == 2:
            json_path = json_path.replace("subject_1", "subject_2")
    # 科目三
    elif session == 3:
        json_path = json_path.replace("session_1", "session_3")
        # 情景2
        if subject == 2:
            json_path = json_path.replace("subject_1", "subject_2")
    # 考试场次
    json_path = json_path.replace("client_path_1", "client_path_" + str(exam_round))
    # read json file
    client_path = json.load(open(json_path, "r", encoding="utf-8"))

    # 处理科目的数据
    if session == 1:
        # 统一经纬度小数位
        client_path["start_point"]["longitude"] = float(format(client_path["start_point"]["longitude"], ".8f"))
        client_path["start_point"]["latitude"] = float(format(client_path["start_point"]["latitude"], ".8f"))
        client_path["end_point"]["longitude"] = float(format(client_path["end_point"]["longitude"], ".8f"))
        client_path["end_point"]["latitude"] = float(format(client_path["end_point"]["latitude"], ".8f"))
        if "breaks" in client_path.keys():
            for i in range(len(client_path["breaks"])):
                client_path["breaks"][i]["break_start_point"]["longitude"] = float(format(client_path["breaks"][i]["break_start_point"]["longitude"], ".8f"))
                client_path["breaks"][i]["break_start_point"]["latitude"] = float(format(client_path["breaks"][i]["break_start_point"]["latitude"], ".8f"))
                client_path["breaks"][i]["break_end_point"]["longitude"] = float(format(client_path["breaks"][i]["break_end_point"]["longitude"], ".8f"))
                client_path["breaks"][i]["break_end_point"]["latitude"] = float(format(client_path["breaks"][i]["break_end_point"]["latitude"], ".8f"))
        # if "newBreaks" in client_path.keys():
        #     for i in range(len(client_path["newBreaks"])):
        #         client_path["newBreaks"][i]["break_start_point"]["longitude"] = float(
        #             format(client_path["newBreaks"][i]["break_start_point"]["longitude"], ".8f"))
        #         client_path["newBreaks"][i]["break_start_point"]["latitude"] = float(
        #             format(client_path["newBreaks"][i]["break_start_point"]["latitude"], ".8f"))
        #         client_path["newBreaks"][i]["break_end_point"]["longitude"] = float(format(client_path["newBreaks"][i]["break_end_point"]["longitude"], ".8f"))
        #         client_path["newBreaks"][i]["break_end_point"]["latitude"] = float(format(client_path["newBreaks"][i]["break_end_point"]["latitude"], ".8f"))
    elif session == 2:
        if subject == 2:
            for i in range(len(client_path["rescue_people"])):
                client_path["rescue_people"][i]["people_point"]["longitude"] = float(
                    format(client_path["rescue_people"][i]["people_point"]["longitude"], ".8f"))
                client_path["rescue_people"][i]["people_point"]["latitude"] = float(
                    format(client_path["rescue_people"][i]["people_point"]["latitude"], ".8f"))
    else:
        # session 3
        for i in range(len(client_path["place_points"])):
            client_path["place_points"][i]["place_point"]["longitude"] = float(format(client_path["place_points"][i]["place_point"]["longitude"], ".8f"))
            client_path["place_points"][i]["place_point"]["latitude"] = float(format(client_path["place_points"][i]["place_point"]["latitude"], ".8f"))
        for i in range(len(client_path["people"])):
            client_path["people"][i]["people_point"]["longitude"] = float(format(client_path["people"][i]["people_point"]["longitude"], ".8f"))
            client_path["people"][i]["people_point"]["latitude"] = float(format(client_path["people"][i]["people_point"]["latitude"], ".8f"))
        for i in range(len(client_path["breaks"])):
            client_path["breaks"][i]["break_start_point"]["longitude"] = float(format(client_path["breaks"][i]["break_start_point"]["longitude"], ".8f"))
            client_path["breaks"][i]["break_start_point"]["latitude"] = float(format(client_path["breaks"][i]["break_start_point"]["latitude"], ".8f"))
            client_path["breaks"][i]["break_end_point"]["longitude"] = float(format(client_path["breaks"][i]["break_end_point"]["longitude"], ".8f"))
            client_path["breaks"][i]["break_end_point"]["latitude"] = float(format(client_path["breaks"][i]["break_end_point"]["latitude"], ".8f"))
        if "newBreaks" in client_path.keys():
            for i in range(len(client_path["newBreaks"])):
                client_path["newBreaks"][i]["break_start_point"]["longitude"] = float(
                    format(client_path["newBreaks"][i]["break_start_point"]["longitude"], ".8f"))
                client_path["newBreaks"][i]["break_start_point"]["latitude"] = float(
                    format(client_path["newBreaks"][i]["break_start_point"]["latitude"], ".8f"))
                client_path["newBreaks"][i]["break_end_point"]["longitude"] = float(format(client_path["newBreaks"][i]["break_end_point"]["longitude"], ".8f"))
                client_path["newBreaks"][i]["break_end_point"]["latitude"] = float(format(client_path["newBreaks"][i]["break_end_point"]["latitude"], ".8f"))
    print("Read client json successfully: Session:%d, Subject:%d, Round:%d" % (session, subject, exam_round))
    return client_path


# Ui界面调用进行预处理
def preprocess(Objdll, s1, ipconfigPath):
    # 读图
    read_map()
    # Objdll1 = cdll.LoadLibrary("./sesson1/DLLtest.dll")
    dlltest.transfer_map(Objdll, nodeList)
    # local_ip = udp.socket.gethostbyname(udp.socket.gethostname())
    # s1.bind((local_ip, 10014))
    cf = configparser.ConfigParser()
    cf.read(ipconfigPath+"/ipconfig.ini")
    local_ip = cf.get("entrant", "ip")
    local_port = cf.get("entrant", "port")
    s1.bind((local_ip, int(local_port)))  # 绑定ip和端口
    # 设置发送（客户端）的ip和端口
    client_ip = cf.get("client", "ip")
    client_port = cf.get("client", "port")
    dest_dir = (client_ip, int(client_port))
    Globalvar.set_send_id_addr(dest_dir)
    # with open("ipconfig.txt", "r") as f:
    #     ip_com = f.read()
    #     local_ip, port = ip_com.split('\n')
    #     print("local ip: " + local_ip + " port: " + port)
    #     s1.bind((local_ip, int(port)))
    # print('Bind UDP on 10014...')
    # 创建线程接收数据
    recv_thread = udp.threading.Thread(target=udp.recvmsg, args=(s1, Objdll))
    recv_thread.start()
    return True


def send_ready(session, subject, examround, s):
    # print(Globalvar.get_send_id_addr())
    # print("current exam round: " + str(examround))
    udp.sentmsg(session, subject, s, Globalvar.get_send_id_addr(), exam_round=examround, info=1)
    print("已准备，等待平台指令")


# Ui界面调用运行科目1，情景1主函数
def session1_main_1(Objdll, s):
    exam_round = 1
    # 判断每场考试是否结束，结束为true，否则为false，初始为true方便第一次发送
    finish = True
    while True:
        if finish:
             # 发送准备指令
            send_ready(1, 1, exam_round, s)
            finish = False
        if Globalvar.get_recv_msg_content():
            Globalvar.set_recv_msg_content(False)
            # 根据报文读取对应科目、情景下的client_path_.json文件
            temp_content = Globalvar.get_msg_content_value()
            examRound = Globalvar.get_exam_round()
            client_path_content = read_client_path(temp_content[0], temp_content[1], exam_round=examRound)
            if dlltest.transfer_client_path(Objdll, client_path_content, temp_content[0], temp_content[1]):
                # 数据传入完成，算法计算完毕，向平台发送完成指令
                udp.sentmsg(temp_content[0], temp_content[1], s, Globalvar.get_send_id_addr(), exam_round=examRound, info=3)
                finish = True
                # 一场考试结束后将考试场次+1
                exam_round += 1
                print("运行成功，准备下次考试")


# 情景2主函数
def session1_main_2(Objdll, s):
    exam_round = 1
    # 判断每场考试是否结束，结束为true，否则为false，初始为true方便第一次发送
    finish = True
    while True:
        if finish:
             # 发送准备指令
            send_ready(1, 2, exam_round, s)
            finish = False
        if Globalvar.get_recv_msg_content():
            Globalvar.set_recv_msg_content(False)
            # 根据报文读取对应科目、情景下的client_path_.json文件
            temp_content = Globalvar.get_msg_content_value()
            examRound = Globalvar.get_exam_round()
            client_path_content = read_client_path(temp_content[0], temp_content[1], exam_round=examRound)
            if dlltest.transfer_client_path(Objdll, client_path_content, temp_content[0], temp_content[1]):
                # 数据传入完成，算法计算完毕，向平台发送完成指令
                udp.sentmsg(temp_content[0], temp_content[1], s, Globalvar.get_send_id_addr(), exam_round=examRound, info=3)
                finish = True
                # 一场考试结束后将考试场次+1
                exam_round += 1
                print("运行成功，准备下次考试")


if __name__ == "__main__":
    # begin_time = datetime.datetime.now()
    # 读map文件夹内的数据
    read_map()

    # 传地图
    Objdll = dlltest.cdll.LoadLibrary("./DLLtest.dll")
    dlltest.transfer_map(Objdll, nodeList)

    # 创建套接字，绑定ip和端口
    s = udp.socket.socket(udp.socket.AF_INET, udp.socket.SOCK_DGRAM)
    local_ip = udp.socket.gethostbyname(udp.socket.gethostname())
    s.bind((local_ip, 10014))
    # s.bind(('202.118.13.194', 10014))
    print('Bind UDP on 10014...')

    # 创建线程接收数据
    recv_thread1 = udp.threading.Thread(target=udp.recvmsg, args=(s, Objdll))
    recv_thread1.start()

    while True:
        if Globalvar.get_recv_msg_content():
            Globalvar.set_recv_msg_content(False)
            # 根据报文读取对应科目、情景下的client_path_.json文件
            temp_content = Globalvar.get_msg_content_value()
            examRound = Globalvar.get_exam_round()
            client_path_content = read_client_path(temp_content[0], temp_content[1], exam_round=examRound)
            if dlltest.transfer_client_path(Objdll, client_path_content, temp_content[0], temp_content[1]):
                # 数据传入完成，算法计算完毕，向平台发送完成指令
                udp.sentmsg(temp_content[0], temp_content[1], s, Globalvar.get_send_id_addr(), exam_round=examRound, info=3)

    # end_time2 = datetime.datetime.now()
    # print("Run time is: " + str((end_time2-begin_time).total_seconds()) + "s")
